package edu.uwosh.cs342.group2.project4.database;

import java.io.*;
import java.net.*;

import android.util.Pair;
import edu.uwosh.cs342.group2.project4.storage.Coordinates;


class PlacesDb {
	private final String APIS_LINK = "https://maps.googleapis.com/maps/api/place/search/json?";
	private final String API_KEY = "AIzaSyCoIl23Zhs2PxS0fAJbTvUApO6rSjHD8iQ";
	
	//https://maps.googleapis.com/maps/api/place/search/json?location=44.024,-88.542&radius=5000&sensor=false&key=AIzaSyCoIl23Zhs2PxS0fAJbTvUApO6rSjHD8iQ
	
	/**
	 * Searches Google Places API for places around
	 * @param coords lat/lon of the location center
	 * @param radius in meters
	 * @param sensor
	 * @param pairs tuple Pair<String, String> being <option, input> array
	 */
	public String SearchPlaces(Coordinates coords, float radius, boolean sensor, Pair<String, String>[] pairs) {
		// TODO: Implement pairs
		URL url = null;
		String queryString = "location=" + coords.getLatitude() + "," + coords.getLongitude() +
				"&radius=" + String.valueOf(radius) +
				"&sensor=" + (sensor ? "true" : "false") +
				"&key=" + API_KEY;
		
		try {
			url = new URL(APIS_LINK + queryString);
		}
		catch(MalformedURLException e) {
			System.out.println("URL for Google Places was malformed");
			return null;
		}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return null;
    	}
		
		InputStream inputStream = null;
    	try {
    		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	inputStream = conn.getInputStream();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return null;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return null;
    	}
    	catch (Exception e) {
    		System.out.println("Bad things happened: " + e.getMessage());
    		return null;
    	}
    	
    	StringBuilder sb = new StringBuilder();
        String line;

        try {
           BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            inputStream.close();
        } catch(Exception e){} 
        return sb.toString();
    	
	}
}
